<?php
/**
 * Created by PhpStorm.
 * User: wo
 * Date: 2019/9/18
 * Time: 17:33
 */
class WithdrawApp extends BackendApp
{
    protected $_withdraw;

    function __construct()
    {
        $this->WithdrawApp();
    }

    function WithdrawApp()
    {
        parent::BackendApp();
        $this->_withdraw = &m('withdraw');
    }

    function index(){
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'status',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'phone_mob',
                'name'  => 'phone_mob',
                'equal' => 'like',
            ),
        ));

        if($_GET['add_time_from']){
            $from_time = strtotime($_GET['add_time_from']);
            $conditions = ' AND create_time >='.$from_time;
            if($_GET['add_time_to']){
                $to_time =strtotime($_GET['add_time_to']);
                $conditions = ' AND create_time >='.$from_time.' AND create_time <='.$to_time;
            }
        }elseif($_GET['add_time_to']){
            $to_time =strtotime($_GET['add_time_to']);
            $conditions = ' AND create_time <='.$to_time;
        }

        $this->assign('add_time_from',$_GET['add_time_from']);
        $this->assign('add_time_to',$_GET['add_time_to']);
        $page = $this->_get_page(10);
        $res = $this->_withdraw->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'limit' => $page['limit'],
            'count' => true,
            'order' => "create_time desc"
        ));

        //格式化type 、status  字段
        foreach($res as $k=>$v){
            //支付类型
            $res[$k]['type_value'] = WithdrawModel::$typeMap[$v['type']];
            //定义状态
            $res[$k]['status_value'] = WithdrawModel::$statusMap[$v['status']];
        }

        $page['item_count'] = $this->_withdraw->getCount();   //获取统计的数据
        $this->_format_page($page);
        $this->assign('res', $res);
        $this->assign('filtered', $conditions? 1 : 0); //是否有查询条件
        $this->import_resource(array('script' => 'inline_edit.js,jquery.ui/jquery.ui.js,jquery.ui/i18n/' . i18n_code() . '.js',
            'style'=> 'jquery.ui/themes/ui-lightness/jquery.ui.css'));
        $this->assign('withdraw_status_list', array(
            1  =>  WithdrawModel::$statusMap[1],
            2  =>  WithdrawModel::$statusMap[2],
            3  =>  WithdrawModel::$statusMap[3],
            4  =>  WithdrawModel::$statusMap[4],
            5  =>  WithdrawModel::$statusMap[5]
        ));
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->display('withdraw.index.html');

    }

    //导出功能
    function excel(){
        $conditions = $this->_get_query_conditions(array(
            array(
                'field' => 'status',
                'equal' => '=',
                'type'  => 'numeric',
            ),
            array(
                'field' => 'phone_mob',
                'name'  => 'phone_mob',
                'equal' => 'like',
            ),
        ));

        if($_GET['add_time_from']){
            $from_time = strtotime($_GET['add_time_from']);
            $conditions = ' AND create_time >='.$from_time;
            if($_GET['add_time_to']){
                $to_time =strtotime($_GET['add_time_to']);
                $conditions = ' AND create_time >='.$from_time.' AND create_time <='.$to_time;
            }
        }elseif($_GET['add_time_to']){
            $to_time =strtotime($_GET['add_time_to']);
            $conditions = ' AND create_time <='.$to_time;
        }
        $res = $this->_withdraw->find(array(
            'conditions'    => '1=1 ' . $conditions,
            'order' => "create_time desc"
        ));
        $to_charset = (CHARSET == 'utf-8') ? substr(LANG, 0, 2) == 'sc' ? 'gbk' : 'big5' : '';
        //格式化type 、status  字段
        $num = 0;
        $data[$num]['ID'] = 'ID';
        $data[$num]['sn'] = '交易订单号';
        $data[$num]['serial_number'] = '交易流水号';
        $data[$num]['type_value'] = '打款类型';
        $data[$num]['number'] = '账户';
        $data[$num]['user_name'] = '真实姓名';
        $data[$num]['money'] = '金额';
        $data[$num]['phone_mob'] = '用户手机号';
        $data[$num]['create_time'] = '申请时间';
        $data[$num]['status_value'] = '状态';
        $data[$num]['return_msg'] = '失败原因';
        foreach($res as $k=>$v){
            $data[$num+1]['ID'] = $v['id'];
            $data[$num+1]['sn'] = $v['sn'];
            $data[$num+1]['serial_number'] = $v['serial_number'].',';
            $data[$num+1]['type_value'] = WithdrawModel::$typeMap[$v['type']];
            $data[$num+1]['number'] = $v['number'];
            $data[$num+1]['user_name'] = $v['user_name'];
            $data[$num+1]['money'] = $v['money'];
            $data[$num+1]['phone_mob'] = $v['phone_mob'];
            $data[$num+1]['create_time'] = date('Y-m-d H:i:s',$v['create_time']);
            $data[$num+1]['status_value'] = WithdrawModel::$statusMap[$v['status']];
            $data[$num+1]['return_msg'] = $v['return_msg'];
            $num++;
        }
        if(!empty($data)){
            $this->export_to_csv($data, date('Y-m-d H:i:s').'提现记录表', $to_charset);
            exit();
        }
        $this->show_warning('数据为空！');
    }

    //操作退款申请
    function operation(){
        $id     = $_POST['id'];
        $status = $_POST['status'];
        $return_msg = $_POST['return_msg'];
        $msg = '参数错误';
        if($id && $status){
            $saveData['status'] = $status;
            $saveData['return_msg'] = $return_msg;

            $save = $this->_withdraw->edit($id,$saveData);
            $msg = '操作失败';
            if($save){
                $msg = '操作成功';
            }
        }
        echo json_encode(array('msg'=>$msg));
        exit();
    }

    //查看退款原因
    function reason(){
        $id = $_POST['id'];
        $code = -1;
        $msg = '参数错误';
        $return_msg = '';
        if($id){
            $info = $this->_withdraw->get(array('conditions'=>"id = ".$id));
            $msg = '信息有误';
            if(!empty($info)){
                $code = 1;
                $msg = '查询成功';
                $return_msg = $info['return_msg'];
            }
        }
        echo json_encode(array('code'=>$code,'msg'=>$msg,'return_msg'=>$return_msg));
        exit();
    }
    //打款方法
    function makeMoney(){
        $id = $_POST['id'];
        $code = -1;
        $msg = '参数错误';
        if($id){
            $memberModel = &m("member");
            $info = $this->_withdraw->get(array("conditions"=>"id = ".$id));
            $msg = '提现信息错误！';
            if($info){
                $msg = '提现状态不符合打款操作！';
                if($info['status'] == 2){
                    try{
                        $memberModel->db->query('start trans');
                        $userInfo = $memberModel->get(array("conditions"=>'user_id = '.$info['user_id']));
                        //查看用什么方式进行打款  $info['type'] == 1 微信  2支付宝
                        if($info['type'] == 1){
                            $memberModel->writeLog('微信打款操作，数据：'.json_encode($info));
                            $msg = '获取openid错误';
                            if($userInfo['openid'] == ''){
                                echo json_encode(array('code'=>$code,'msg'=>$msg));
                                exit();
                            }
                            $data['number'] = $info['number'];
                            $data['money'] = $info['money'];
                            $data['sn'] = $info['sn'];
                            $data['openid'] = $userInfo['openid'];
                            $memberModel->writeLog('微信打款操作，传入微信数据：'.json_encode($data));
                            $res = WithdrawModel::wxTransfer($data);
                            $memberModel->writeLog('微信打款操作，微信回调结果：'.json_encode($res));
                            $msg = $res['err_code_des'];
                            $saveData['status'] = 5;
                            $saveData['return_msg'] = $msg;
                            if($res['return_code'] == 'SUCCESS' && $res['result_code'] == "SUCCESS"){
                                $saveData['status'] = 4;
                                $saveData['serial_number'] = $res['payment_no'];
                            }else{
                                $msg = $res['return_msg'];
                            }

                        }elseif($info['type'] == 2){
                            $memberModel->writeLog('支付宝打款操作，数据：'.json_encode($info));
                            $data['number'] = $info['number'];
                            $data['money'] = $info['money'];
                            $data['sn'] = $info['sn'];
                            $data['user_name'] = $info['user_name'];
                            $memberModel->writeLog('支付宝打款操作，传入支付宝数据：'.json_encode($data));
                            $res = WithdrawModel::aliTransfer($data);
                            $memberModel->writeLog('支付宝打款操作，支付宝回调结果：'.json_encode($res));
                            $msg = $res['alipay_fund_trans_uni_transfer_response']['sub_msg'];
                            $saveData['status'] = 5;
                            $saveData['return_msg'] = $msg;
                            if($res['alipay_fund_trans_uni_transfer_response']['code'] == 10000){
                                $saveData['status'] = 4;
                                $saveData['serial_number'] = $res['alipay_fund_trans_uni_transfer_response']['order_id'];
                                $saveData['return_msg'] = $res['alipay_fund_trans_uni_transfer_response']['msg'];
                            }elseif($res['alipay_fund_trans_uni_transfer_response']['code'] == 20000){
                                $memberModel->db->query('rollback');
                                echo json_encode(array("code"=>$code,"msg"=>$msg));
                                exit();
                            }
                        }

                        $saveWithdraw = $this->_withdraw->edit($id,$saveData);
                        if(!$saveWithdraw){
                            $memberModel->db->query('rollback');
                            $msg = '保存失败：失败原因，修改数据失败';
                            echo json_encode(array("code"=>$code,"msg"=>$msg));
                            exit();
                        }

                        //打款失败  账户余额进行回滚
                        if($saveData['status'] == 5){
                            $saveDataMember['commission']    = $userInfo['commission'] + $info['money'];
                            $saveDataMember['commission_dj'] = $userInfo['commission_dj'] + $info['money'];
                            $saveMember = $memberModel->edit($info['user_id'],$saveDataMember);
                            if(!$saveDataMember){
                                $memberModel->db->query('rollback');
                                $msg = '保存失败：失败原因，回滚金额失败';
                                echo json_encode(array("code"=>$code,"msg"=>$msg));
                                exit();
                            }
                            $code = 1;
                            $msg = '操作完成：打款失败，失败原因：'.$msg;
                            $memberModel->db->query('commit');
                            echo json_encode(array("code"=>$code,"msg"=>$msg));
                            exit();
                        }
                        $code = 1;
                        $msg = '操作完成：打款成功';
                        $memberModel->db->query('commit');
                    }catch(\Exception $e){
                        $msg = '网络错误';
                        echo json_encode(array("code"=>$code,"msg"=>$msg));
                        exit();
                    }
                }
            }
        }
        echo json_encode(array("code"=>$code,"msg"=>$msg));
        exit();
    }


}